<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label="二级集团：">
            <Select v-model="dataToQuery.twoLevelOrgId" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgCode" :key="item.orgCode">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="检查时间：">
            <DatePicker class="query-form-el" v-model="dataToQuery.dateRange" format="yyyy-MM-dd" type="daterange"
                        placement="bottom-start" placeholder="请选择查询时间"
                        :clearable="true"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="exporToFile" class="ivu-btn-add1" icon="md-cloud-download">导出</Button>
          <Button @click="query" style="float:left" class="ivu-btn-query" type="primary" icon="md-search">查询</Button>
          <Button @click="reset" style="float:left" class="ivu-btn-reset">重置</Button>

        </Col>
      </Row>
    </Form>
    <Row class="chartRow">
      <Col span="15" style="padding-right: 8px;padding-left: 0;height: 100%">
        <div class="singleForm">
          <div class="standardTitleItem">
            <p style="line-height: 27px;font-size:18px;height:27px;color:red">▎ </p>
            <p class="formTitle">问题分类</p>
          </div>
          <div style="width:100%;height:300px;flex-grow: 1" ref="questionContainer"></div>
        </div>
      </Col>
      <Col span="9" style="padding-left: 8px;padding-right: 0;height: 100%">
        <div class="singleForm">
          <div class="standardTitleItem">
            <p style="line-height: 27px;font-size:18px;height:27px;color:red">▎ </p>
            <p class="formTitle">隐患等级</p>
          </div>
          <div style="width:100%;height:300px;flex-grow: 1" ref="yinhuanContainer"></div>
        </div>
      </Col>
    </Row>
    <Table :loading="loading" ref='table' width="100%" class="tableClass" :height="300"
           border :columns="columns1" :data="tableData"></Table>
    <companyNotice ref="companyNotice"></companyNotice>
  </Layout>
</template>
<script>
import {Api} from '../../../api'
import {sessionStorage} from '@/common/cacheUtils.js';
import {formatDate} from '@/tools/index';
import * as echarts from 'echarts'
import pageCommonFunction from '@/components/pageCommonFunction.js';
import companyNotice from './companyNoticeTable.vue'

export default {
  name: "companyNoticeStatistic",
  components: {companyNotice},
  data() {
    return {
      ...this.createCommonDataField(),
      loading: false,
      questionLoading: false,
      show: false,
      barNameMap: {},
      yinhuanLoading: false,
      questionContainer: null,
      yinhuanContainer: null,
      twoLevelOrgs: [],
      tableHeight: 10,
      tableData: [],
      columns1: [
        {key: 'index', title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '企业名称', minWidth: 150, align: 'center'},
        {
          key: 'questionNum',
          title: '发现问题数量',
          minWidth: 150,
          align: 'center',
          render: (h, params) => {
            return h('A', {
              props: {
                type: 'primary',
                size: 'small'
              },
              on: {
                click: () => {
                  this.showNoticeItem(params.row);
                }
              }
            }, params.row.questionNum)
          }
        },
        {key: 'finishNum', title: '完成整改数量', minWidth: 150, align: 'center'},
        {key: 'exceedNum', title: '超期', minWidth: 150, align: 'center'},
        {
          key: 'finishRate', title: '完成率', minWidth: 150, align: 'center', render: (h, params) => {
            let value = (params.row.finishNum * 100) / params.row.questionNum;
            return h('div', [
              h('span', value.toFixed(0) + '%' || '--')
            ]);
          }
        }
      ]
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 110;
    this.queryTwoOrgInfo();
    this.dataToQuery.dateRange = [new Date().getFullYear() + '-01-01', new Date()]
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    showNoticeItem(data) {
      let queryData = {
        ...this.dataToQuery,
        ...data,
      }
      this.$refs.companyNotice.open(queryData);
    },
    queryTwoOrgInfo() {
      this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
        this.twoLevelOrgs = res.data.data
      }).catch(e => {
      })

    },
    exporToFile() {
      let i = 0
      this.$refs.table.exportCsv({
        filename: '隐患整改通知统计',
        data: this.tableData.map(item => {
          i = i + 1;
          item.index = i
          item.finishRate = ((item.finishNum * 100) / item.questionNum).toFixed(0) + '%'
        })
      });
    },
    query() {
      this.loading = true;
      if (this.dataToQuery.dateRange && this.dataToQuery.dateRange[0] != "" && this.dataToQuery.dateRange[1] != "") {
        this.dataToQuery.startDate = formatDate(new Date(this.dataToQuery.dateRange[0]), 'yyyy-MM-dd');
        this.dataToQuery.endDate = formatDate(new Date(this.dataToQuery.dateRange[1]), 'yyyy-MM-dd');
      }
      this.loadQuestionContainer();
      this.loadYinhuanContainer();
      this.$http.get(Api.queryCompanyNoticeTableStatistic + "/" + sessionStorage('userId').getObject('userId').companyId,
          {params: this.dataToQuery}).then(res => {
        this.tableData = res.data.data
        this.loading = false;
      }).catch(e => {
      })
    },
    loadQuestionContainer() {
      let _this = this;
      this.questionLoading = true;
      _this.$http.get(Api.queryCompanyNoticeQuestionStatistic + "/" + sessionStorage('userId').getObject('userId').companyId, {params: this.dataToQuery}).then((res) => {
        if (res.data.status == 200) {
          _this.questionLoading = false;
          _this.questionContainer = echarts.init(_this.$refs.questionContainer);
          let option = this.getQuestionContainerOption();
          option.xAxis[0].data = res.data.data.xAxis;
          option.series[0].data = res.data.data.series[0].data;
          option.series[1].data = res.data.data.series[1].data;
          _this.barNameMap = res.data.data.nameMap
          _this.questionContainer.setOption(option);
          _this.questionContainer.on("click", riskDetails);

          function riskDetails(param) {
            // console.log(param);
            event.stopPropagation() // 阻止冒泡
            console.log(_this.barNameMap[param.name]);
            _this.showNoticeItem({'issuePosition': _this.barNameMap[param.name]})
          }
        }
      });
    },
    loadYinhuanContainer() {
      let _this = this;
      _this.yinhuanLoading = true;
      _this.$http.get(Api.queryCompanyNoticeYinhuanStatistic + "/" + sessionStorage('userId').getObject('userId').companyId, {params: this.dataToQuery}).then((res) => {
        if (res.data.status == 200) {
          _this.yinhuanLoading = false;
          this.yinhuanContainerRef = echarts.init(this.$refs.yinhuanContainer);
          let option = this.getYinhuanContainerOption();
          option.series[0].data = res.data.data;
          this.yinhuanContainerRef.setOption(option);
          _this.yinhuanContainerRef.on("click", (param) => {
            event.stopPropagation() // 阻止冒泡
            console.log(param);
            _this.showNoticeItem({'issueLevel': param['data']['code']})

          });
        }
      });
    },
    getQuestionContainerOption() {
      let option = {
        tooltip: {
          textStyle: {
            fontSize: 12
          },
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['问题数量', '已完成整改'],
          top: 'bottom',
          left: 'center',
          textStyle: {
            fontSize: 12
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisLabel: {
              //x轴文字的配置
              show: true,
              interval: 0,//使x轴文字显示全
              textStyle: {
                fontSize: 9,
                fontFamily: 'HiraginoSansGB-W3, HiraginoSansGB',
                color: 'rgb(51,51,51)',
                lineHeight: 14
              },
              formatter: function (params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 1; //一行显示几个字
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = "";
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;
                  }
                } else {
                  newParamsName = params;
                }
                return newParamsName;
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [{
          name: "问题数量", emphasis: {focus: "series"}, type: "bar",
          itemStyle: {
            color: this.linear(
                '#1999FF',
                '#82CDFF'
            )
          }
        }, {
          name: "已完成整改", emphasis: {focus: "series"}, type: "bar",
          itemStyle: {
            color: this.linear(
                '#F9A23E',
                '#FBD784'
            )
          }
        }
        ]
      };
      return option;
    },
    getYinhuanContainerOption() {
      let option = {
        tooltip: {
          trigger: 'item',
          textStyle: {
            fontSize: 12
          }
        },
        legend: {
          orient: 'vertical',
          top: 'center',
          left: '60%',
          type: 'scroll',
          formatter: function (name) {
            // 获取legend显示内容
            let data = option.series[0].data;
            let total = 0;
            let tarValue = 0;
            for (let i = 0, l = data.length; i < l; i++) {
              total += data[i].value;
              if (data[i].name == name) {
                tarValue = data[i].value;
              }
            }
            if (total == 0) {
              return name + '  ' + tarValue + '  ' + '0%';
            } else {
              let p = (tarValue / total * 100).toFixed(2);
              return name + '  ' + tarValue + '  ' + p + '%';
            }
          },
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['60%', '80%'],
            center: ['30%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              normal: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2,
              }
            },
            color: [
              this.linear(
                  '#82CDFF',
                  '#1999FF'
              ),
              this.linear(
                  '#FFBDC1',
                  '#CA65E5'
              )
            ],
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: false,
                fontSize: '12',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: []
          }
        ]
      };
      return option;
    },
    linear(startColor, endColor) {
      // 4个方位参数依次为右、下、左、上，（0 0 0 1）代表从正上方开始
      // 数组, 用于配置颜色的渐变过程. 每一项为一个对象, 包含offset和color两个参数. offset的范围是0 ~ 1, 用于表示位置
      return {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
          offset: 0, color: startColor // 0% 处的颜色
        }, {
          offset: 1, color: endColor // 100% 处的颜色
        }],
        globalCoord: false // 缺省为 false
      }
    },
  }
}
</script>
<style scoped>
.chartRow {
  flex-grow: 10;
  margin-top: 10px;
  background-color: #F5F7F9;
}

.standardTitleItem {
  display: flex;
  flex-direction: row;
  justify-content: left;
  margin-right: 20px;
}

.singleForm {
  width: 100%;
  height: 100%;
  background-color: white;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.formTitle {
  font-size: 18px;
  font-family: HiraginoSansGB-W3, HiraginoSansGB;
  font-weight: normal;
  color: #333333;
  line-height: 27px;
  flex-grow: 1;
}

.tableClass >>> .ivu-table-tip {
  overflow-x: hidden;
}

.query-form .ivu-btn-add1 {
  height: 30px;
  background: #FFFFFF;
  border: 1px solid #EF5350;
  border-radius: 4px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  color: #EF5350;
  float: right
}

</style>
